package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.ClassroomMapper;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.mapper.UserRoleMapper;
import cn.tedu.knows.portal.model.Classroom;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.UserRole;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import cn.tedu.knows.portal.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2022-03-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    @Transactional
    public void registerStudent(RegisterVO registerVO) {
        QueryWrapper<Classroom> query=new QueryWrapper<>();
        query.eq("invite_code",registerVO.getInviteCode());
        Classroom classroom=classroomMapper.selectOne(query);
        if (classroom==null){
            throw  new ServiceException("邀请码错误");
        }
        User user=userMapper.findUserByUsername(registerVO.getPhone());
        if (user!=null){
            throw new ServiceException("手机号已经被注册");
        }
        PasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd="{bcrypt}"+encoder.encode(registerVO.getPassword());
        User stu=new User()
                .setUsername(registerVO.getPhone())
                .setNickname(registerVO.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);
        int num=userMapper.insert(stu);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }
        UserRole userRole=new UserRole()
                .setRoleId(2)
                .setUserId(stu.getId());
        num=userRoleMapper.insert(userRole);
        if (num!=1){
            throw new ServiceException("数据库异常");
        }
    }

    //声明两个讲师缓存的集合
    private List<User> teachers=new CopyOnWriteArrayList<>();
    private Map<String,User> teacherMap=new ConcurrentHashMap<>();

    @Override
    public List<User> getTeachers() {
        if (teachers.isEmpty()){
            synchronized (teachers){
                teachers.clear();
                teacherMap.clear();
                List<User>list=userMapper.findTeachers();
                teachers.addAll(list);
                for (User u:list){
                    teacherMap.put(u.getNickname(),u);
                }
            }
        }
        return teachers;
    }

    @Override
    public Map<String, User> getTeacherMap() {
        if (teacherMap.isEmpty()){
            getTeachers();
        }
        return teacherMap;
    }

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public UserVO getUserVO(String username) {
        User user=userMapper.findUserByUsername(username);
        int collections=questionMapper.countCollectByUserId(user.getId());
        int questions=questionMapper.countQuestionsByUserId(user.getId());
        UserVO userVO=new UserVO()
                .setId(user.getId())
                .setUsername(user.getUsername())
                .setNickname(user.getNickname())
                .setQuestions(questions)
                .setCollections(collections);
        return userVO;

    }
}
